

var sdf = new SimpleDateFormat("yyyy");
var yyyy_MM_dd_HH_mm_ss_PARSER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
var creditCardAllData
var dataList = new ArrayList();
load("js/luaclient.js")

var v6_boc_java_funcs = {

    openHomePage : function(){

        var html = get("https://ebsnew.boc.cn/boc15/login.html");
        storeDataToFile(context, html, "1_login.html");
        context.put("loginIframe", html)
    },
    //检查代理是否可用
    checkProxyAvailable: function () {
        logger.info("BOC task:{}，检查当前代理是否可用{}", context.get(LUA_TASK_KEY), context.get(LUA_TASK_PROXY))
        var loginIframe = context.get("loginIframe")
        var checkProxyRight = function (loginIframe) {
            return !(loginIframe.contains("代理服务器没有响应") || loginIframe.contains("无法显示此页"))
        }
        var getProxyErrorMsg = function (html) {
            return "代理ip异常"
        }
        return assertTrueOrThrowException(loginIframe, checkProxyRight, getProxyErrorMsg)
    },
    checkControlAvailable: function () {
        return true
    },
    checkTargetWebsiteAvailable: function(){
        return true;
    },
    login:function () {

        inputUserName();
        inputPassWord();
        inputImg();
    },
    crawl: crawl,
    needRefreshHomePageOrNot : function() {
        return false;
    },
    needResetEnvironment:function(){
        return true;
    },
    exitLogin: function () {
    }

}
// 检查、输入用户名
function inputUserName() {
    var loginType = context.get(Constants.LUA_TASK_LOGIN_TYPE);
    logger.info("中国银行 taskKey:{} loginType:{}",context.get(LUA_TASK_KEY),loginType);
    var checkBocLoginParam = {}
    checkBocLoginParam.statuts = '';
    var loginNoTmp = checkUserNameAndPasswdIfLegal(checkBocLoginParam);
    var checkLoginParamFunc = function (checkBocLoginParam) {
        return equals(checkBocLoginParam.statuts,'')
    }
    var getCheckLoginParamErrorMsgFunc = function (checkBocLoginParam) {
        return checkBocLoginParam.errorMsg
    }
    assertTrueOrThrowException(checkBocLoginParam, checkLoginParamFunc, getCheckLoginParamErrorMsgFunc)
    // 输入用户名
    var loginResult = {}
    inputAndCheckUserName(loginNoTmp, loginResult);
    var checkLoginFunc = function(loginResult){
        return equals(loginResult.statuts, "OK")
    }
    var getLoginErrorMsgFunc = function(loginResult) {
        return loginResult.errorMsg
    }
    assertTrueOrThrowException(loginResult, checkLoginFunc, getLoginErrorMsgFunc)
}

function checkUserNameAndPasswdIfLegal(checkBocLoginParam){
    var loginType = context.get(Constants.LUA_TASK_LOGIN_TYPE);
    var loginNoTmp = getLoginParams(context)[0].trim();
    var password = context.get(Constants.LUA_TASK_TOKEN);
    context.put("LOGININPUT",loginNoTmp)
    logger.info("中国银行 taskkey:{}, 用户登录方式为：{}",context.get(Constants.LUA_TASK_KEY), loginType);
    if (loginType.contains(LoginType.CARDNO.toString())) {
        context.put("LOGINSTYLE","0")
        //密码判断
        if (password.length() != 6 || !isAllNum(password)) {
            logger.error("密码输入错误只能是6位数字,输入的密码长度{}", password.length());
            checkBocLoginParam.statuts = 'WROONGPASSWORD';
            checkBocLoginParam.errorMsg = '用户名或密码错误，请重新输入';
        }
    } else if (LoginType.USERNAME.toString().equals(loginType)) {
        context.put("LOGINSTYLE","1")
    }
    //判断用户名是否6-20位
    if (!(StringUtils.isNoneBlank(loginNoTmp) && loginNoTmp.length() >= 6 && loginNoTmp.length() <= 20)) {
        checkBocLoginParam.statuts = 'WROONGPASSWORD';
        checkBocLoginParam.errorMsg = '用户名或密码错误，请重新输入';
    }
    return loginNoTmp;
}

function inputAndCheckUserName(loginNoTmp, loginResult){
    show()
    var typeResult = luaFuncs.typeUsername(loginNoTmp);
    hide();
    logger.info("username ok : {},taskkey:{}", typeResult, context.get(Constants.LUA_TASK_KEY));

    var rightuser = luaFuncs.checkUsername();
    logger.info("is right user:{},taskkey:{}", rightuser, context.get(Constants.LUA_TASK_KEY));
    if (StringUtils.isNotBlank(rightuser)) {
        if (rightuser.equals("true")) {
            logger.info("username is valid:{},taskkey：{}", loginNoTmp, context.get(Constants.LUA_TASK_KEY));
            loginResult.statuts = "OK"
        } else if(rightuser.contains("对不起，操作未成功！")){
            loginResult.statuts = "WRONGNET";
            loginResult.errorMsg = "对不起，操作未成功！";
        } else {
            loginResult.statuts = "WRONGNET";
            loginResult.errorMsg = rightuser;
        }
    } else {
        throw new BankException(BankConstants.BALO_23001_10, "脚本执行错误");
    }
}
//输入密码
function inputPassWord(){
    var passwd = context.get(Constants.LUA_TASK_TOKEN);
    logger.info("中国银行 taskKey:{} 即将输入去空格后的密码，长度：{}",context.get(LUA_TASK_KEY),passwd.length());
    show();
    var pwdResult = luaFuncs.inputpwd(passwd);
    hide()
    var checkLoginPwdFunc = function(pwdResult){
        return pwdResult
    }
    var getLoginPwdErrorMsgFunc = function(pwdResult) {
        return "密码因控件输入错误"
    }
    return assertTrueOrThrowException(pwdResult, checkLoginPwdFunc, getLoginPwdErrorMsgFunc)
}

function getImgByAnotherWay() {
    var dirs =   luaFuncs.getimage_by_id("captcha_debitCard");
    if (StringUtils.isNotBlank(dirs) && "image_id_not_exist".equals(dirs)){
        dirs =luaFuncs.getimage_by_id("captcha_creditCard");
    }
    return dirs;
}

function inputImg() {
    var dir = "";
    // 判断是否刷新图片验证码,先点击登录,是否包含captcha元素
    var onlyCaptcha = luaFuncs.isCaptcha();
    logger.info("图片验证码是否失去焦点后就刷新,验证码类型:{}", onlyCaptcha);
    if (onlyCaptcha.equals("captcha")) {
        var loginStatus = luaFuncs.presslogin();// 通过返回值判断是否登陆成功
        logger.info("通过返回值判断是否登陆成功:{}", loginStatus);
        //这种情况表示不需要图片验证码
        if ("logined".equals(loginStatus)) {
            dir = loginStatus;
        } else {
            dir = luaFuncs.getimage_by_id("captcha");
        }

    } else if(onlyCaptcha.equals("captcha-cardtype")){
        if (context.get(Constants.LUA_TASK_CARD_TYPE).equals("DEBITCARD")) {
            dir = luaFuncs.getimage_by_id("captcha_debitCard");
        } else {
            dir = luaFuncs.getimage_by_id("captcha_creditCard");
        }
    }else if(onlyCaptcha.equals("false")){
        throw new BankException(BankConstants.BALO_99602_50,"判断是否刷新图片验证码失败");
    }
    logger.info("中国银行taskkey:{}，获取的图片验证码的路径:{}",context.get(Constants.LUA_TASK_KEY), dir);

    var loginResult = {}
    // 默认为图片验证码错误
    loginResult.errorMsg = "图片验证码错误"
    // 当下述条件存在的时候，代表可以直接返回
    loginResult.dir = dir
    var checkLogin = function(loginResult) {
        if (!StringUtils.isEmpty(loginResult.dir) && "logined".equals(loginResult.dir)) {
            return true;
        } else if (StringUtils.isNotBlank(loginResult.dir) && "image_id_not_exist".equals(loginResult.dir)) {
            loginResult.dir = getImgByAnotherWay();
            if (StringUtils.isNotBlank(loginResult.dir) && "image_id_not_exist".equals(loginResult.dir)) {
                //进入到此处说明借记卡、信用卡都没有获取到图片验证码
                //错误类型1：页面中没有获取到图片验证码
                loginResult.errorMsg = "登录超时";
                return false;
            }
        }
        if (!StringUtils.isEmpty(loginResult.dir) && !"error".equals(loginResult.dir)) {
            context.put(TASK_IMG_PATH, loginResult.dir);
            context.put(TASK_IMG_REGEX, "[0-9a-zA-Z]{4}");
            var yzm = waitImgCodeBySecondsByJs(context, 240, true, 3);
            logger.info("中国银行 taskkey:{},获取到的图片验证码:{}", context.get(Constants.LUA_TASK_KEY),yzm);
            var res = luaFuncs.inputcaptcha(yzm);
            if (res.contains("false")) {
                return false;
            }
        } else {
            return false;
        }

        // 检查登录
        var loginok = luaFuncs.loginok(context.get("LOGINSTYLE"));
        logger.info("中国银行 taskkey:{}, 登录是否成功：{}",context.get(Constants.LUA_TASK_KEY), loginok);
        if (loginok.equals('true')){
            return true;
        }else if (loginok.contains("验证码输入错误，请重试")){
            loginResult.errorMsg = "图片验证码错误";
            return false;
        }else if (loginok.contains("对不起，操作未成功！")){
            loginResult.errorMsg = "对不起，操作未成功！";
            return false;
        }else {
            loginResult.errorMsg = loginok;
            return false;
        }
    };
    var getCheckLoginErrorMsgFunc = function (loginResult) {
        return loginResult.errorMsg
    }
    return assertTrueOrThrowException(loginResult, checkLogin, getCheckLoginErrorMsgFunc)
}

function getLoginCookie(){
    var cookiesResult = luaFuncs.getLoginCookie();
    if(null==cookiesResult||null==JSON.parse(cookiesResult)){
        throw new BankException(BALO_99601_30, "获取Cookie失败");
    }
    var cookies = JSON.parse(cookiesResult).getString("cookie");
    var isGetMcvIdCorrectFunc = function(cookies){
        return !("empty").equals(cookies);
    }
    var getMcvIdErrorMsgFunc = function () {
        return "登录超时"
    }
    assertTrueOrThrowException(cookies,isGetMcvIdCorrectFunc,getMcvIdErrorMsgFunc);
    logger.info("中国银行 taskKey = {}, 获取登录之后的cookie为{}", context.get(LUA_TASK_KEY), cookies);

    if(StringUtils.isNotBlank(cookies)){
        cookies = cookies.substring(cookies.indexOf("JSESSIONID"));
        context.put("cookies",cookies);
    }else{
        throw new BankException(BankConstants.BALO_99601_30, "获取Cookie失败");
    }
}

function crawl() {
    getLoginCookie();
    var data = null;
    var result = null;
    if (context.get(Constants.LUA_TASK_CARD_TYPE).equals("CREDITCARD")) {
        if("1".equals(context.get("LOGINSTYLE"))){
            logger.info("中国银行 taskKey = {}, 用户名获取信用卡数据", context.get(LUA_TASK_KEY));
            data = getUserCreditData();
            storeDataToFile(context, data, "1_userCreditBills.txt");
        } else {
            logger.info("中国银行 taskKey = {}, 卡号获取信用卡数据", context.get(LUA_TASK_KEY));
            data = getCardCreditData();
            storeDataToFile(context, data, "1_cardCreditBills.txt");
        }
        context.put("crawlCreditData", data);
    } else {
        if("1".equals(context.get("LOGINSTYLE"))){
            logger.info("中国银行 taskKey = {}, 用户名获取借记卡数据", context.get(LUA_TASK_KEY));
            data = getUserDebitData();
            storeDataToFile(context, data, "1_userDebitBills.txt");
        } else {
            logger.info("中国银行 taskKey = {}, 卡号获取借记卡数据", context.get(LUA_TASK_KEY));
            data = getCardDebitData();
            storeDataToFile(context, data, "1_cardDebitBills.txt");
        }
        context.put("crawlDebitData", data);
    }
    logger.info("中国银行 taskKey:{}, 抓取中国银行卡数据完成，准备解析...", context.get(LUA_TASK_KEY));

    if (context.get(LUA_TASK_CARD_TYPE).equals("CREDITCARD")) {
        analysisCreditData();
    } else {
        if("1".equals(context.get("LOGINSTYLE"))){
            analysisUserDebitData();
        } else {
            analysisCardDebitData();
        }
    }
    context.put(ALL_DATA, dataList);
    logger.info("中国银行 taskKey:{},解析中国银行卡数据完成...", context.get(LUA_TASK_KEY));
}

//用户名获取借记卡数据
var userDebitData = {};
var userDebitList = new ArrayList();
var userDebitTradeList ={};
userDebitTradeList["List"]=userDebitList;
userDebitData["userDebitTradeList"]=userDebitTradeList;
function getUserDebitData(){
    //封装需要的参数
    var map = new HashMap();
    var header = new HashMap();
    var request = new HashMap();
    request.put("method","PsnCommonQueryOprLoginInfo");
    request.put("conversationId",null);
    request.put("params",null);
    var list = new ArrayList();
    list.add(request);
    map.put("header", header);
    map.put("request", list);
    var headers = new HashMap();
    headers.put("bfw-ctrl", "json");//必须
    headers.put("Cookie",context.get("cookies"));//必须
    //登录信息
    retryContinueUrl(map,headers,userDebitData,"logininfo","登录信息","1",true);

    //账户信息
    request.put("method","PsnCommonQueryAllChinaBankAccount");
    var accountId;
    var  result2 = retryUrl(map,headers,userDebitData,"allAccount","账户信息","2",true);
    if(result2.flag){
        var allAccount = result2.data;
        if(allAccount.length==0){
            logger.info("该用户没有获取到借记卡信息...");
            throw new BankException(BankConstants.BALO_20304_30, "该用户没有获取到借记卡信息");
        }
        accountId =allAccount[0].getString("accountId");
        logger.info("accountId:"+accountId);
    }

    //余额信息
    var params = new HashMap();
    params.put("accountId",accountId);
    request.put("method","PsnSVRAccQuery");
    request.put("params",params);
    retryContinueUrl(map,headers,userDebitData,"AccQuery","余额信息","1",true);

    //明细信息
    request.put("method","PsnAccountQueryAccountDetail");
    retryContinueUrl(map,headers,userDebitData,"accountDetail","明细信息","1",true);

    getUserDebitDetails(request,map,headers,accountId,getsixmonth(5),getsixmonth(-1));
    getUserDebitDetails(request,map,headers,accountId,getsixmonth(11),getsixmonth(5));
    getUserDebitDetails(request,map,headers,accountId,getsixmonth(17),getsixmonth(11));
    getUserDebitDetails(request,map,headers,accountId,getsixmonth(23),getsixmonth(17));
    logger.info("中国银行 taskKey:{},用户名获取的借记卡数据userDebitData:{}",context.get(LUA_TASK_KEY),JSON.toJSONString(userDebitData));
    return JSON.toJSONString(userDebitData);
}
function getUserDebitDetails(request,map,headers,accountId,month1,month2){
    logger.info("中国银行 taskKey:{},用户名获取借记卡传入月份startDate:{} ~ endDate:{}",context.get(LUA_TASK_KEY),month1,month2);
    var conversationId = getUserDebitId(request,map,headers);
    var params = new HashMap();
    params.put("_refresh","true");
    params.put("accountId",accountId);
    params.put("cashRemit","");
    params.put("currency","001");
    params.put("currentIndex","0");
    params.put("startDate",month1);
    params.put("endDate",month2);
    params.put("pageSize",10);
    request.put("method","PsnAccountQueryTransferDetail");
    request.put("conversationId",conversationId);
    request.put("params",params);
    var result = retryContinueUrl(map,headers,null,"",month1+"~"+month2+"月份用户名获取的借记卡明细数据条数","1",false);
    if(result.flag){
        var recordNumber = result.data.getString("recordNumber");
        if(null!=recordNumber){
            params.put("pageSize",recordNumber);
            request.put("params",params);
            var result = retryContinueUrl(map,headers,null,"",month1+"~"+month2+"用户名获取的借记卡明细数据","1",false);
            if(result.flag){
                var detailsArray = result.data.getJSONArray("List");
                if(null!=detailsArray&&detailsArray.length>0){
                    for(var j=0;j<detailsArray.length;j++){
                        userDebitList.add(detailsArray[j]);
                    }
                }
            }
        }
    }
}
function getUserDebitId(request,map,headers){
    request.put("method","PSNCreatConversation");
    request.put("conversationId",null);
    request.put("params",null);
    var result = retryUrl(map,headers,null,"","获取用户名借记卡查询ID","3",false);
    if(result.flag){
        return result.data;
    }else{
        throw new BankException(BankConstants.BALO_20304_30, "该用户获取用户名借记卡查询ID失败");
    }
}
//用户名解析借记卡理财版数据
function analysisUserDebitData() {
    createCardData();
    userDebitCardExists();
    analysisUserDebitGeneralInfo();
    analysisUserDebitAccount();
    analysisUserDebitAccountDetail();
    analysisUserDebitTradeDetail();
}
//判断借记卡是否存在
function userDebitCardExists(){
    var content = context.get("crawlDebitData");
    var json = JSON.parseObject(content);
    context.put("json",json)
    if (StringUtils.isBlank(content)) {
        logger.info("中国银行 taskKey:{},抓取到的借记卡信息为空", context.get(LUA_TASK_KEY));
        throw new BankException(BankConstants.BALO_20304_30, "该用户没有获取到借记卡信息");
    }
}
//解析基本信息
function analysisUserDebitGeneralInfo(){
    var json = context.get("json");
    if (json !== null && json.containsKey("logininfo")) {
        var logininfo = json.getJSONObject("logininfo");
        if (logininfo != null) {
            creditCardAllData.setOpenTime(yyyy_MM_dd_PARSER.parse(replaceAll(logininfo.getString("createDate"),"/", "-")));
            creditCardAllData.setNameOnCard(logininfo.getString("customerName"));
        }
    }
}
//解析账户信息
function analysisUserDebitAccount(){
    var json = context.get("json");
    if (json != null && json.containsKey("allAccount")) {
        var allAccount = json.getJSONArray("allAccount");
        if (allAccount != null && allAccount.size() > 0) {
            var account = allAccount.get(0);
            var nickName = account.getString("nickName");
            if (StringUtils.isNoneBlank(nickName)) {
                creditCardAllData.setBankName(nickName);
            }
            var cardNum = account.getString("accountNumber");
            creditCardAllData.setFullCardNum(cardNum);// 卡号
            creditCardAllData.setCardNum(cardNum.substring(cardNum.length() - 4, cardNum.length()));
            creditCardAllData.setOpenBank(account.getString("branchName"));
            creditCardAllData.setCardId(UUID.randomUUID().toString());
        }
    }
}
//解析账户详情
function analysisUserDebitAccountDetail(){
    var json = context.get("json");
    if (json != null && json.containsKey("accountDetail")) {
        var balance = new BigDecimal(0);
        var accountDetail = json.getJSONObject("accountDetail");
        var accountDetaiList = accountDetail.getJSONArray("accountDetaiList");
        if (accountDetaiList !== null && accountDetaiList.size() > 0) {
            var deposits = creditCardAllData.getDeposits();
            for each(var object in accountDetaiList){
                var data = object;
                balance = balance.add(data.getBigDecimal("availableBalance"));
                var d = new CreditCardTimeDeposit();
                d.setDepositType(getZhongguoCurrencyType(data.getString("currencyCode")));
                d.setBalance(data.getBigDecimal("availableBalance"));
                d.setCurrencyType("CNY");
                // only deposit type known
                d.setDepositType("活期储蓄");
                d.setDepositDate(yyyy_MM_dd_PARSER.parse(replaceAll(data.getString("openDate"),"/", "-")));
                deposits.add(d);
            }
        }
        creditCardAllData.setBalance(balance);
    }
}
//解析交易明细
function analysisUserDebitTradeDetail(){
    var json = context.get("json");
    if (json !== null && json.containsKey("userDebitTradeList")) {
        logger.info("获取到userDebitTradeList信息,开始解析userDebitTradeList");
        var tradelist = json.getJSONObject("userDebitTradeList");
        if (null !== tradelist && tradelist.size() > 0) {
            var monthinfo = new HashMap();
            logger.info("tradelist:"+tradelist);
            var sublist = tradelist.getJSONArray("List");
            for (var j = 0; j < sublist.size(); j++) {
                var s = sublist.getJSONObject(j);
                var month = s.getString("paymentDate");
                if (StringUtils.isNotBlank(month)) {
                    month = replaceAll(month,"/", "-");
                    var monthidx = month.substring(0, 7);
                    if (!monthinfo.containsKey(monthidx)) {
                        var bill = new BillAllData();
                        bill.setBillType("");
                        bill.setNewBalance(null);
                        bill.setMinPayment(null);
                        bill.setLastBalance(null);
                        bill.setPaymentDueDate(null);
                        bill.setUsdCashLimit(null);
                        bill.setCashLimit(null);
                        bill.setUsdCreditLimit(null);
                        bill.setCreditLimit(null);
                        bill.setUsdInterest(null);
                        bill.setInterest(null);
                        bill.setUsdLastBalance(null);
                        bill.setUsdLastPayment(null);
                        bill.setLastPayment(null);
                        bill.setUsdMinPayment(null);
                        bill.setUsdNewBalance(null);
                        bill.setUsdNewCharges(null);
                        bill.setNewCharges(null);
                        bill.setBillMonth(monthidx);
                        bill.setBankName("中国银行");
                        bill.setBillType("");
                        bill.setBillId(UUID.randomUUID().toString());
                        bill.setBillDate(yyyy_MM_dd_PARSER.parse(monthidx + "-01"));
                        bill.setShoppingSheets(new ArrayList());
                        monthinfo.put(monthidx, bill);
                    }
                    var bill = monthinfo.get(monthidx);
                    var e = new Expense();
                    //初始化数据
                    e.setBalance(null);
                    e.setId(UUID.randomUUID().toString());
                    e.setDescription(s.getString("businessDigest"));
                    e.setBalance(s.getBigDecimal("balance"));
                    e.setTransChannel(s.getString("transChnl"));// 交易渠道
                    e.setTransAddr(s.getString("chnlDetail"));// 交易地点
                    e.setOppositeBank(s.getString("payeeAccountName"));// 对方银行
                    e.setOppositeCardNo(s.getString("payeeAccountNumber"));// 对方卡号
                    e.setNameOnOppositeCard(s.getString("furInfo"));// 对方用户名
                    var trans_dateStr = replaceAll(s.getString("paymentDate"),"/", "-");
                    if(null!=trans_dateStr){
                        var trans_date = trans_dateStr +" 00:00:00";
                        e.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date));
                    }
                    e.setPostDate(yyyy_MM_dd_PARSER.parse(replaceAll(s.getString("paymentDate"),"/", "-")));
                    e.setCurrencyType(getZhongguoCurrencyType(s.getString("currency")));
                    e.setAmountMoney(s.getBigDecimal("amount").negate());
                    e.setCategory(classify(e.getDescription()));
                    e.setOrderIndex(bill.getShoppingSheets().size() + 1);
                    e.setCardNum(creditCardAllData.getCardNum());
                    bill.getShoppingSheets().add(e);
                }
            }
            creditCardAllData.setBills(new ArrayList(monthinfo.values()));
        }
    }
}


//卡号获取借记卡数据
var cardDebitData = {};
var cardDebitList = new ArrayList();
var cardDebitTradeList ={};
cardDebitTradeList["List"]=cardDebitList;
cardDebitData["cardDebitTradeList"]=cardDebitTradeList;
function getCardDebitData(){
    //封装需要的参数
    var map = new HashMap();
    var header = new HashMap();
    var request = new HashMap();
    request.put("method","PsnAccBocnetQryLoginInfo");
    request.put("conversationId",null);
    request.put("params",null);
    var list = new ArrayList();
    list.add(request);
    map.put("header", header);
    map.put("request", list);
    var headers = new HashMap();
    headers.put("bfw-ctrl", "json");//必须
    headers.put("Cookie",context.get("cookies"));//必须
    //登录信息
    var accountSeq;
    var  result = retryUrl(map,headers,cardDebitData,"logininfo","登录信息","1",true);
    if(result.flag){
        var logininfo = result.data;
        accountSeq = logininfo.getString("accountSeq");
        logger.info("accountSeq:"+accountSeq);
    }
    //基本信息
    var params = new HashMap();
    params.put("accountSeq",accountSeq);
    request.put("method","PsnAccBocnetQryDebitDetail");
    request.put("params",params);
    retryContinueUrl(map,headers,cardDebitData,"generalinfo","基本信息","1",true);

    //现金信息
    request.put("method","PsnAccBocnetQryEcashDetail");
    request.put("params",params);
    retryContinueUrl(map,headers,cardDebitData,"cashdetail","现金信息","1",true);
    getCardDebitDetails(request,map,headers,accountSeq,getsixmonth(5),getsixmonth(-1));
    getCardDebitDetails(request,map,headers,accountSeq,getsixmonth(11),getsixmonth(5));
    getCardDebitDetails(request,map,headers,accountSeq,getsixmonth(17),getsixmonth(11));
    getCardDebitDetails(request,map,headers,accountSeq,getsixmonth(23),getsixmonth(17));
    logger.info("中国银行 taskKey:{},卡号获取的借记卡数据cardDebitData:{}",context.get(LUA_TASK_KEY),JSON.toJSONString(cardDebitData));
    return JSON.toJSONString(cardDebitData);
}
function getCardDebitDetails(request,map,headers,accountSeq,month1,month2){
    logger.info("中国银行 taskKey:{},卡号获取借记卡传入月份startDate:{} ~ endDate:{}",context.get(LUA_TASK_KEY),month1,month2);
    var conversationId = getCardDebitId(request,map,headers);
    var recordNumber= null;;
    var params = new HashMap();
    params.put("_refresh","true");
    params.put("accountSeq",accountSeq);
    params.put("cashRemit","");
    params.put("currency","001");
    params.put("currentIndex","0");
    params.put("startDate",month1);
    params.put("endDate",month2);
    params.put("pageSize",10);
    request.put("method","PsnAccBocnetQryDebitTransDetail");
    request.put("conversationId",conversationId);
    request.put("params",params);
    var result = retryContinueUrl(map,headers,null,"",month1+"~"+month2+"月份卡号获取借记卡明细数据条数","1",false);
    if(result.flag){
        var recordNumber = result.data.getString("recordNumber");
        if(null!=recordNumber){
            params.put("pageSize",recordNumber);
            request.put("params",params);
            var result = retryContinueUrl(map,headers,null,"",month1+"~"+month2+"卡号获取的借记卡明细数据","1",false);
            if(result.flag){
                var detailsArray = result.data.getJSONArray("List");
                if(null!=detailsArray&&detailsArray.length>0){
                    for(var j=0;j<detailsArray.length;j++){
                        cardDebitList.add(detailsArray[j]);
                    }
                }
            }
        }
    }
}
function getCardDebitId(request,map,headers){
    request.put("method","PsnAccBocnetCreateConversation");
    request.put("conversationId",null);
    request.put("params",null);
    var result = retryUrl(map,headers,null,"","获取卡号借记卡查询ID","3",false);
    if(result.flag){
        return result.data;
    }else{
        throw new BankException(BankConstants.BALO_20304_30, "该用户获取卡号借记卡查询ID失败");
    }
}
function getsixmonth(i) {
    var d = new Date();
    d.setMonth(d.getMonth() - i);
    var date = d.getDate();
    if (date < 10) {
        date = "0" + date;
    }
    var year = Integer.parseInt(sdf.format(d));
    var month = d.getMonth();
    if (month <= 0) {
        month = 12;
        year = year - 1;
    }
    if (month < 10) {
        month = "0" + month;
    }
    return year + "/" + month + "/" + date;
}
//卡号解析借记卡数据
function analysisCardDebitData() {
    createCardData();
    cardDebitCardExists();
    analysisCardDebitGeneralInfo();
    analysisCardDebitTradeDetail();
}
//解析卡号抓取借记卡是否存在借记卡
function cardDebitCardExists(){
    var content = context.get("crawlDebitData");
    var json = JSON.parseObject(content);
    context.put("json",json)
    if (StringUtils.isBlank(content)) {
        logger.info("中国银行 taskKey:{},卡号抓取到的借记卡信息为空", context.get(LUA_TASK_KEY));
        throw new BankException(BankConstants.BALO_20304_30, "该用户没有获取到借记卡信息");
    }
}
//解析卡号抓取借记卡基本信息
function analysisCardDebitGeneralInfo(){
    var json = context.get("json");
    if (json !== null && json.containsKey("generalinfo")) {
        try {
            logger.info("获取到generalinfo信息,开始解析generalinfo");
            var generalinfo = json.getJSONObject("generalinfo");
            var logininfo = json.getJSONObject("logininfo");
            creditCardAllData.setOpenTime(yyyy_MM_dd_PARSER.parse(replaceAll(generalinfo.getString("openDate"),"/", "-")));
            creditCardAllData.setOpenBank(generalinfo.getString("openBank"));
            creditCardAllData.setNameOnCard(logininfo.getString("name"));
            var accountnum = logininfo.getString("accountNumber");
            if (StringUtils.isNotBlank(accountnum)) {
                creditCardAllData.setFullCardNum(accountnum);
                creditCardAllData.setCardNum(accountnum.substring(accountnum.length() - 4));
            }
            // 账户详情,余额信息
            var accountDetaiList = generalinfo.getJSONArray("accountDetaiList");
            var balance = new BigDecimal(0);
            if (null !== accountDetaiList && accountDetaiList.size() > 0) {
                // get card deposit information
                var deposits =  creditCardAllData.getDeposits();
                for (var i = 0; i < accountDetaiList.size(); i++) {
                    var inf = accountDetaiList.getJSONObject(i);
                    var d = new CreditCardTimeDeposit();
                    d.setDepositType(getZhongguoCurrencyType(inf.getString("currencyCode")));
                    d.setBalance(inf.getBigDecimal("bookBalance"));
                    d.setCurrencyType("CNY");
                    balance = balance.add(d.getBalance());
                    d.setDepositType("活期储蓄");
                    d.setDepositDate(yyyy_MM_dd_PARSER.parse(replaceAll(inf.getString("openDate"),"/", "-")));
                    deposits.add(d);
                }
            }
            creditCardAllData.setBalance(balance);
        } catch (e) {
            logger.error("中国银行 taskKey:{} getDeposit()方法中开始解析generalinfo信息失败。原因：{}",context.get(LUA_TASK_KEY),e);
        }
    }
}
//解析卡号抓取借记卡交易详情
function analysisCardDebitTradeDetail(){
    var json = context.get("json");
    if (json != null && json.containsKey("cardDebitTradeList")) {
        try {
            logger.info("获取到cardDebitTradeList信息,开始解析cardDebitTradeList");
            var tradelist = json.getJSONObject("cardDebitTradeList");
            if (null !== tradelist) {
                var monthinfo = new HashMap();
                var sublist = tradelist.getJSONArray("List");
                for (var j = 0; j < sublist.size(); j++) {
                    var s = sublist.getJSONObject(j);
                    var month = s.getString("paymentDate");
                    if (StringUtils.isNotBlank(month)) {
                        month = replaceAll(month,"/", "-");
                        var monthidx = month.substring(0, 7);
                        if (!monthinfo.containsKey(monthidx)) {
                            var bill = new BillAllData();
                            bill.setBillType("");
                            bill.setInterest(null);
                            bill.setCashLimit(null);
                            bill.setNewBalance(null);
                            bill.setMinPayment(null);
                            bill.setLastBalance(null);
                            bill.setPaymentDueDate(null);
                            bill.setUsdCashLimit(null);
                            bill.setCashLimit(null);
                            bill.setUsdCreditLimit(null);
                            bill.setCreditLimit(null);
                            bill.setUsdInterest(null);
                            bill.setInterest(null);
                            bill.setUsdLastBalance(null);
                            bill.setUsdLastPayment(null);
                            bill.setLastPayment(null);
                            bill.setUsdMinPayment(null);
                            bill.setUsdNewBalance(null);
                            bill.setUsdNewCharges(null);
                            bill.setNewCharges(null);
                            bill.setBillMonth(monthidx);
                            bill.setBankName("中国银行");
                            bill.setBillType("");
                            bill.setBillId(UUID.randomUUID().toString());
                            bill.setBillDate(yyyy_MM_dd_PARSER.parse(monthidx + "-01"));
                            bill.setShoppingSheets(new ArrayList());
                            monthinfo.put(monthidx, bill);
                        }
                        var bill = monthinfo.get(monthidx);
                        var e = new Expense();
                        e.setId(UUID.randomUUID().toString());
                        e.setDescription(s.getString("businessDigest"));
                        e.setBalance(s.getBigDecimal("balance"));
                        e.setTransChannel(s.getString("transChnl"));// 交易渠道
                        e.setTransAddr(s.getString("chnlDetail"));// 交易地点
                        e.setOppositeBank(s.getString("payeeAccountName"));// 对方银行
                        e.setOppositeCardNo(s.getString("payeeAccountNumber"));// 对方卡号
                        e.setNameOnOppositeCard(s.getString("furInfo"));// 对方用户名
                        var trans_dateStr = replaceAll(s.getString("paymentDate"),"/", "-");
                        if(null!=trans_dateStr){
                            var trans_date = trans_dateStr +" 00:00:00";
                            e.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date));
                        }
                        e.setPostDate(yyyy_MM_dd_PARSER.parse(replaceAll(s.getString("paymentDate"),"/", "-")));
                        e.setCurrencyType(getZhongguoCurrencyType(s.getString("currency")));
                        e.setAmountMoney(s.getBigDecimal("amount").negate());
                        var category = classify(e.getDescription());
                        if(StringUtils.isBlank(category)){
                            category = "SHOPPING"
                        }
                        e.setCategory(category);
                        e.setOrderIndex(bill.getShoppingSheets().size() + 1);
                        e.setCardNum(creditCardAllData.getCardNum());
                        bill.getShoppingSheets().add(e);
                    }
                }
                creditCardAllData.setBills(new ArrayList(monthinfo.values()));
            }
        } catch (e) {
            logger.error("中国银行 taskKey:{} 解析tradelist时出错，信息：{}",context.get(LUA_TASK_KEY),e);
        }
    }
}

//用户名获取信用卡数据
var dt = {};
dt["accountInfo"] = {};          //信用卡账户信息
dt["generalInfo"] = {};          //信用卡基本信息
dt["unDownBill"] = {};           //未出账单
dt["unBillTotal"] = {}			//未出账单合计
dt["billMonth"] = {};
dt["billMonthDetail"] = {};
//用户名抓取信用卡数据
function  getUserCreditData(){
    var map = new HashMap();
    var header = new HashMap();
    var request = new HashMap();
    request.put("method","PSNCreatConversation");
    request.put("conversationId",null);
    request.put("params",null);
    var list = new ArrayList();
    list.add(request);
    map.put("header", header);
    map.put("request", list);
    var headers = new HashMap();
    headers.put("bfw-ctrl", "json");            //必须
    headers.put("Cookie",context.get("cookies"));//必须

    var conversation = getUserCreditId(request,map,headers);
    var accountArg = JSON.parseArray("['103','104','107']");
    var  params = new HashMap();
    params.put("accountType",accountArg);
    request.put("method","PsnCommonQueryAllChinaBankAccount");
    request.put("conversationId",conversation);
    request.put("params",params);
    var accountId;
    var  result = retryUrl(map,headers,dt,"accountInfo","用户信息","2",true);
    if(result.flag){
        var accountInfo = result.data;
        if(null==accountInfo||accountInfo.length==0){
            logger.info("该用户没有获取到信用卡信息...");
            throw new BankException(BankConstants.BALO_20304_30, "该用户没有获取到信用卡信息...");
        }
        accountId = accountInfo[0].getString("accountId");
        logger.info("accountId:"+accountId);
    }

    var params1 = new HashMap();
    params1.put("accountId",accountId);
    params1.put("currentIndex","0");
    params1.put("pageSize","10");
    params1.put("_refresh","false");
    request.put("method","PsnCrcdQueryFutureBill");
    request.put("conversationId",conversation);
    request.put("params",params1);
    retryContinueUrl(map,headers,dt,"unDownBill","未出账单","1",true);


    var params2 = new HashMap();
    params2.put("accountId",accountId);
    request.put("method","PsnCrcdQueryFutureBillTotalIncome");
    request.put("conversationId",null);
    request.put("params",params2);
    retryContinueUrl(map,headers,dt,"unBillTotal","未出账单合计","2",true);


    request.put("method","PsnCrcdQueryGeneralInfo");
    retryContinueUrl(map,headers,dt,"generalInfo","基本信息","1",true);

    request.put("method","PsnCrcdQryAnnualFeeFreeInfo");
    var billDay;
    var result1 = retryContinueUrl(map,headers,null,"","账单日","1",false);
    if(result1.flag){
        var feeInfo = result1.data;
        if(null==feeInfo||feeInfo.length==0){
            logger.info("该用户没有获取到账单日信息...");
            throw new BankException(BankConstants.BALO_20304_30, "该用户没有获取到账单日信息...");
        }
        var feeInfoListArray = result1.data.getJSONArray("feeInfoList");
        var billDay = feeInfoListArray[0].getString("billDay");
        dt["billDay"] = billDay;
        logger.info("账单日billDay:"+billDay);
    }
    var billDayList = getBillDayList(billDay);
    logger.info("中国银行 taskKey:{},需要抓取的月份账单集合billDayList：{}",context.get(LUA_TASK_KEY),billDayList);
    for(var b=0;b<billDayList.length;b++){
        getUserCreditBill(request,map,headers,accountId,billDayList[b]+"");
    }
    logger.info("中国银行 taskKey:{},用户名抓取的理财版信用卡数据：{}",context.get(LUA_TASK_KEY),JSON.toJSONString(dt));
    return JSON.toJSONString(dt);
}
function getUserCreditBill( request, map, headers, accountId, statementMonth) {
    var conversation = getUserCreditId(request,map,headers);
    var params = new HashMap();
    params.put("accountId",accountId);
    params.put("statementMonth",statementMonth);
    request.put("method","PsnCrcdQueryBilledTrans");
    request.put("conversationId",conversation);
    request.put("params",params);
    var billResult = retryContinueUrl(map,headers,null,"",statementMonth+"月份账单","1",false);
    if(billResult.flag){
        dt["billMonth"][statementMonth+""] = billResult.data;
        var crcdCustomerInfo  = billResult.data.getJSONObject("crcdCustomerInfo");
        var billDate = crcdCustomerInfo.getString("billDate");
        var creditcardId = crcdCustomerInfo.getString("creditcardId");
        if(StringUtils.isNotBlank(billDate)&&StringUtils.isNotBlank(creditcardId)){
            getUserCreditDetails(request,map,headers,creditcardId,conversation,billDate,statementMonth);
        }else{
            logger.info("{}月份的参数billDate:{},creditcardId:{}获取错误，无法抓取账单...",statementMonth,billDate,creditcardId);
        }
    }

}
function getUserCreditDetails(request,map,headers,creditcardId,conversation, billDate, statementMonth) {
    var params = new HashMap();
    params.put("accountType","104");
    params.put("creditcardId",creditcardId+"");
    params.put("lineNum","100");
    params.put("pageNo","1");
    params.put("primary","");
    params.put("statementMonth",billDate+"");
    params.put("_refresh","true");
    request.put("method","PsnCrcdQueryBilledTransDetail");
    request.put("conversationId",conversation);
    request.put("params",params);
    var result = retryContinueUrl(map,headers,null,"",statementMonth+"月份账单明细","1",false);
    if(result.flag){
        dt["billMonthDetail"][statementMonth+""] = result.data;
    }

}
function getUserCreditId(request,map,headers){
    request.put("method","PSNCreatConversation");
    request.put("conversationId",null);
    request.put("params",null);
    var result = retryUrl(map,headers,null,"","获取用户名信用卡查询ID","3",false);
    if(result.flag){
        return result.data;
    }else{
        throw new BankException(BankConstants.BALO_20304_30, "获取用户名信用卡查询ID失败");
    }
}

//卡号抓取信用卡数据
function  getCardCreditData(){
    var map = new HashMap();
    var header = new HashMap();
    var request = new HashMap();
    request.put("method","PsnAccBocnetQryLoginInfo");
    request.put("conversationId",null);
    request.put("params",null);
    var list = new ArrayList();
    list.add(request);
    map.put("header", header);
    map.put("request", list);
    var headers = new HashMap();
    headers.put("bfw-ctrl", "json");                       //必须
    headers.put("Cookie",context.get("cookies"));          //必须

    //账户信息
    var accountInfo = retryUrl(map,headers,dt,"accountInfo","账户信息","1",true);
    if(!accountInfo.flag){
        throw new BankException(BankConstants.BALO_20304_30, "获取账户信息失败");
    }
    var accountId = accountInfo.data.getString("accountSeq");
    logger.info("accountId:"+accountId);

    //基本信息
    var  params = new HashMap();
    params.put("accountSeq",accountId);
    params.put("currency","");
    request.put("method","PsnAccBocnetQueryGeneralInfo");
    request.put("params",params);
    var generalInfo = retryUrl(map,headers,dt,"generalInfo","基本信息","1",true);
    if(!generalInfo.flag){
        throw new BankException(BankConstants.BALO_20304_30, "获取基本信息失败");
    }
    var billDay = generalInfo.data.getString("billDate");
    dt["billDay"] = billDay;
    logger.info("billDay:"+billDay);


    //未出账单
    var conversationId = getCardCreditId(request,map,headers);
    params = new HashMap();
    params.put("accountSeq",accountId);
    params.put("pageSize","10");
    params.put("refresh","10");
    params.put("currentIndex",1);
    request.put("method","PsnAccBocnetQryCrcdUnsettledBills");
    request.put("conversationId",conversationId);
    request.put("params",params);
    retryContinueUrl(map,headers,dt,"unDownBill","未出账单","1",true);

    //未出账单统计
    params = new HashMap();
    params.put("accountSeq",accountId);
    request.put("method","PsnAccBocnetQryCrcdUnsettledTotal");
    request.put("conversationId",null);
    request.put("params",params);
    retryContinueUrl(map,headers,dt,"unBillTotal","未出账单合计","2",true);

    //抓取月份账单
    var billDayList = getBillDayList(billDay);
    logger.info("卡号抓取信用卡数据，需要抓取的月份months:{}",billDayList.toString());
    for(var i =0;i<billDayList.length;i++){
        getCardCreditBill(request,map,headers,billDayList[i],accountId);
    }
    logger.info("中国银行 taskKey:{},卡号抓取的普通版信用卡数据：{}",context.get(LUA_TASK_KEY),JSON.toJSONString(dt));
    return JSON.toJSONString(dt);
}
function getCardCreditBill(request,map,headers,statementMonth,accountId){
    //月份账单
    var conversationId = getCardCreditId(request,map,headers);
    var params = new HashMap();
    params.put("accountSeq",accountId);
    params.put("statementMonth",statementMonth);
    request.put("method","PsnAccBocnetQryCrcdStatement");
    request.put("conversationId",conversationId);
    request.put("params",params);
    var billResult = retryContinueUrl(map,headers,null,"",statementMonth+"月份账单","1",false);
    if(billResult.flag){
        dt["billMonth"][statementMonth+""] = billResult.data;
        var crcdCustomerInfo  = billResult.data.getJSONObject("crcdCustomerInfo");
        var creditcardId = crcdCustomerInfo.getString("creditcardId");
        var billDate = crcdCustomerInfo.getString("billDate");
        if(StringUtils.isNotBlank(billDate)&&StringUtils.isNotBlank(creditcardId)){
            getCardCreditDetails(request,map,headers,statementMonth,billDate,creditcardId,conversationId);
        }else{
            logger.info("{}月份的参数billDate:{},creditcardId:{}获取错误，无法抓取账单...",statementMonth,billDate,creditcardId);
        }
    }
}
function getCardCreditDetails(request,map,headers,statementMonth,monthDay,creditcardId,conversationId){
    //月份账单明细
    var params = new HashMap();
    params.put("creditcardId",creditcardId);
    params.put("statementMonth",monthDay);
    params.put("accountType","104");
    params.put("primary","");
    params.put("_refresh","true");
    params.put("lineNum","50");
    params.put("pageNo","1");
    request.put("method","PsnAccBocnetQryCrcdStatementDetail");
    request.put("conversationId",conversationId);
    request.put("params",params);
    var result = retryContinueUrl(map,headers,null,"",statementMonth+"月份账单明细","1",false);
    if(result.flag){
        dt["billMonthDetail"][statementMonth+""] = result.data;
    }
}
function  getCardCreditId(request,map,headers){
    request.put("method","PsnAccBocnetCreateConversation");
    request.put("conversationId",null);
    request.put("params",null);
    var result = retryUrl(map,headers,null,"","获取卡号信用卡查询ID","3",false);
    if(result.flag){
        return result.data;
    }else{
        throw new BankException(BankConstants.BALO_20304_30, "该用户获取卡号信用卡查询ID失败");
    }
}
//信用卡获取需要抓取的月份
function getBillDayList(billDay){
    var billDayList = new Array();
    if(StringUtils.isNotBlank(billDay)){
        var date = new Date();
        var day = date.getDate();
        var month = date.getMonth()+1;
        var year = Integer.parseInt(sdf.format(date));
        if(day<=billDay){
            if (month > 1) {
                month--;
            } else {
                month = 12;
                year--;
            }
        }
        for (i = 0; i < 12; i++) {
            if (month < 10) {
                billDayList.push(year + "/0" + month);
            } else {
                billDayList.push(year + "/" + month);
            }
            if (month > 1) {
                month--;
            } else {
                month = 12;
                year--;
            }
        }
    }
    return billDayList;
}

var unBillMonth
var billDay
//解析信用卡数据
function analysisCreditData(){
    createCardData();
    creditCardExists();
    analysisCreditGeneralInfo();
    analysisCreditDoneBills();
    analysisCreditBillDay();
    analysisCreditUnDoneBills();
    logger.info("中国信用卡 taskKey:{}，解析中国银行理财版数据完成...",context.get(LUA_TASK_KEY));
}
//判断信用卡是否存在
function creditCardExists(){
    var content = context.get("crawlCreditData");
    if (StringUtils.isBlank(content)) {
        logger.info("中国银行 taskKey:{},抓取到的信用卡信息为空", context.get(LUA_TASK_KEY));
        throw new BankException(BankConstants.BALO_20304_30, "该用户没有获取到信用卡信息");
    }
    var json = JSON.parseObject(content);
    context.put("json",json);
    //判断是否关联信用卡
    if (json != null && json.containsKey("accountInfo")) {
        logger.info("判断是否关联信用卡accountInfo...");
        var account = null
        if("1".equals(context.get("LOGINSTYLE"))){
            account = json.getJSONArray("accountInfo");
            if(null==account||account.length==0){
                logger.info("该用户没有获取到信用卡信息...");
                throw new BankException(BankConstants.BALO_20304_30, "该用户没有获取到信用卡信息");
            }
        }else{
            account = json.getJSONObject("accountInfo");
            if(null==account){
                logger.info("该用户没有获取到信用卡信息...");
                throw new BankException(BankConstants.BALO_20304_30, "该用户没有获取到信用卡信息");
            }
        }
    }
}
//解析账户基本信息
function analysisCreditGeneralInfo(){
    var json = context.get("json");
    if (json != null && json.containsKey("generalInfo")) {
        logger.info("开始解析账户基本信息generalInfo...");
        var general = json.getJSONObject("generalInfo");
        if (null == general) {
            logger.info("中国银行 taskKey:{},获取到的账户基本信息为null ,停止填充基本信息，继续填充其他信息 ", context.get(LUA_TASK_KEY));
        } else {
            creditCardAllData.setCardId(UUID.randomUUID().toString());
            var accountnum = general.getString("acctNum");
            if (StringUtils.isNotBlank(accountnum)) {
                creditCardAllData.setCardNum(accountnum.substring(accountnum.length() - 4));
                creditCardAllData.setFullCardNum(accountnum);
            }
            creditCardAllData.setNameOnCard(general.getString("acctName"));
            creditCardAllData.setOpenBank(general.getString("acctBank"));
            if(StringUtils.isNotBlank(general.getString("startDate"))){
                creditCardAllData.setOpenTime(yyyy_MM_dd_PARSER.parse(general.getString("startDate")));
            }
            var actList = general.getJSONArray("actList");
            if (null != actList && actList.length > 0) {
                var act = actList.get(0);
                creditCardAllData.setBalance(act.getBigDecimal("toltalBalance"));
                creditCardAllData.setCashLimit(act.getBigDecimal("cashLimit"));
                creditCardAllData.setCashBalance(act.getBigDecimal("cashBalance"));
                creditCardAllData.setCreditLimit(act.getBigDecimal("dividedPayLimit"));
            }
        }
    }
}
//解析已出账单
function analysisCreditDoneBills(){
    unBillMonth = null
    var json = context.get("json");
    /**
     * 解析已出账单,totalBill是数组类型
     *注意一个问题，就是已出账单和已出账单明细的数组月份对应问题
     */
    if (json !== null && json.containsKey("billMonthDetail")) {
        logger.info("中国银行 taskKey:{},获取到已出账单信息和已出账单明细,开始解析billMonthDetail...",context.get(LUA_TASK_KEY));
        var detail = json.getJSONObject("billMonthDetail");
        for (var key in detail) {
            var billMonth = json.getJSONObject("billMonth");
            for (var key1 in billMonth) {
                if(key==key1){
                    logger.info("中国银行 taskKey:{},匹配成功的key:{}",context.get(LUA_TASK_KEY),key1);
                    var bill = billMonth[key1];
                    var billAllData = new BillAllData();
                    //设置公共部分
                    billAllData.setBankName("中国银行");
                    billAllData.setBillId(UUID.randomUUID().toString());
                    billAllData.setBillType("DONE");
                    //设置crcdAccountInfoList信息
                    var crcdAccountInfoList = JSON.parseObject(bill).getJSONArray("crcdAccountInfoList");
                    if(null!=crcdAccountInfoList&&crcdAccountInfoList.length>0){
                        for (var i = 0; i < crcdAccountInfoList.length; i++) {
                            var c = crcdAccountInfoList.get(i);
                            if (c.getString("acntType").contains("CNY")) {
                                billAllData.setLastPayment(c.getBigDecimal("totalDeposit").multiply(new BigDecimal(-1)));
                                billAllData.setMinPayment(c.getBigDecimal("lowestRepayAmount"));
                                billAllData.setCreditLimit(c.getBigDecimal("cdtLmtAmt"));
                                billAllData.setLastBalance(c.getBigDecimal("dealCnt"));
                                billAllData.setNewCharges(c.getBigDecimal("totalExpend"));
                                billAllData.setCashLimit(c.getBigDecimal("periodGetCashCreditLimit"));
                                var reapyDt = replaceAll(c.getString("reapyDt"),"/", "-");
                                if (null != reapyDt && !"".equals(reapyDt)) {
                                    billAllData.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(reapyDt));
                                }else{
                                    logger.info("中国银行 taskKey:{},{}账单日中的reapyDt 为空",context.get(LUA_TASK_KEY),c.getString("billDt"));
                                    //中国银行的还款日是账单日后20天
                                    var billDt = replaceAll(c.getString("billDt"),"/", "-")
                                    if(null != billDt && !"".equals(billDt)){
                                        var now =  yyyy_MM_dd_PARSER.parse(billDt);
                                        now.setDate(now.getDate()+20);
                                        var nowStr = "-"+(now.getMonth()+1)+"-"+now.getDate();
                                        var year = billDt.substring(0,4);
                                        billAllData.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(year+nowStr));
                                        logger.info("中国银行 taskKey:{},PaymentDueDate设置成功",context.get(LUA_TASK_KEY));
                                    }
                                }
                                billAllData.setLastBalance(c.getBigDecimal("lastTermAcntBal"));
                            } else {
                                billAllData.setUsdLastPayment(c.getBigDecimal("totalDeposit"));
                                billAllData.setUsdCreditLimit(c.getBigDecimal("cdtLmtAmt"));
                                billAllData.setUsdLastBalance(c.getBigDecimal("dealCnt"));
                                billAllData.setUsdNewCharges(c.getBigDecimal("totalExpend"));
                                billAllData.setUsdCashLimit(c.getBigDecimal("periodGetCashCreditLimit"));
                                //var blfalg = c.getInteger("lastTermAcntBalflag");
                                billAllData.setUsdLastBalance(c.getBigDecimal("lastTermAcntBal"));
                            }
                        }
                    }
                    //设置crcdCustomerInfo信息
                    var crcdCustomerInfo = JSON.parseObject(bill).getJSONObject("crcdCustomerInfo");
                    if(null!=crcdCustomerInfo){
                        var billDate_json = crcdCustomerInfo.getString("billDate");
                        //以下逻辑用来确定未出账单的账单日  --start
                        if(null==unBillMonth){
                            unBillMonth = billDate_json;
                        }else{
                            if((new Date(billDate_json)).after(new Date(unBillMonth))){
                                unBillMonth = billDate_json;
                            }
                        }
                        //确定未出账单的账单日  --end
                        billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(replaceAll(billDate_json,"/", "-")));
                        billAllData.setNewBalance(crcdCustomerInfo.getBigDecimal("curTermBalance1"));
                        var billMonth = billDate_json.substring(0,billDate_json.lastIndexOf("/"));
                        billAllData.setBillMonth(replaceAll(billMonth,"/", "-"));
                    }
                    //补全信息
                    if (billAllData.getCashLimit() == null) {
                        billAllData.setCashLimit(creditCardAllData.getCashLimit());
                    }
                    if (billAllData.getCreditLimit() == null) {
                        billAllData.setCreditLimit(creditCardAllData.getCreditLimit());
                    }
                    var bil = detail[key];
                    var transList = JSON.parseObject(bil).getJSONArray("transList");
                    var shop = new ArrayList();
                    var installments = new ArrayList();
                    var cidx = 1;
                    //设置购物明细
                    //设置月份账单明细信息
                    //此处存在一个缺陷就是要保证月份账单和月份明细账单要对应上
                    if(null!=transList&&transList.length>0){
                        for (var i = 0; i < transList.length; i++) {
                            var t = transList.get(i);
                            var installment = new Installment();
                            var s = new Expense();
                            //初始化数据
                            s.setBalance(null);
                            s.setDescription(replaceAll(t.getString("dealDesc")," ", ""));
                            s.setCategory(classify(s.getDescription()));

                            if(t.getString("loanSign").equals("CRED")){
                                s.setAmountMoney(t.getBigDecimal("dealCnt").negate());
                            } else {
                                s.setAmountMoney(t.getBigDecimal("dealCnt"));
                            }
                            var trans_dateStr = replaceAll(t.getString("dealDt"),"/", "-");
                            if(null!=trans_dateStr){
                                var trans_date = trans_dateStr + " 00:00:00";
                                s.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date));
                            }
                            s.setPostDate(yyyy_MM_dd_PARSER.parse(replaceAll(t.getString("checkDt"),"/", "-")));
                            s.setId(UUID.randomUUID().toString());
                            s.setCurrencyType(t.getString("acntType"));
                            s.setOrderIndex(cidx++);
                            s.setCardNum(creditCardAllData.getCardNum());
                            shop.add(s);
                            parseInstallment(installment, t, billAllData.getBillId());
                            //描述不为空才保存
                            if (StringUtils.isNotBlank(installment.getInstallmentDesc())
                                || StringUtils.isNotBlank(installment.getHandingfeeDesc())){
                                installments.add(installment);
                            }
                        }
                        billAllData.setShoppingSheets(shop);
                        //设置分期分期
                        if (installments.size() > 0) {
                            var fees = new HashMap();
                            var bills = new ArrayList();
                            for (var i = 0; i < installments.size(); i++) {
                                var installment = installments.get(i);
                                if (StringUtils.isNotBlank(installment.getHandingfeeDesc())) {
                                    var installment2 = installments.get(0);
                                    if (StringUtils.isNotBlank(installment2.getHandingfeeDesc())) {
                                        fees.put(bills.size(), installment);
                                    } else {
                                        fees.put(bills.size() - 1, installment);
                                    }
                                } else {
                                    bills.add(installment);
                                }
                            }
                            for (var i = 0; i < bills.size(); i++) {
                                var fee = fees.get(i);
                                var bill = bills.get(i);
                                if (fee !== null) {
                                    bill.setHandingFee(fee.getHandingFee());
                                    bill.setHandingfeeDesc(fee.getHandingfeeDesc());
                                }
                            }
                            installments.clear();
                            installments.addAll(bills);
                        }
                        billAllData.setInstallments(installments);
                    }
                    creditCardAllData.getBills().add(billAllData);
                }
            }
        }
    }
}
//解析账单日
function analysisCreditBillDay(){
    billDay = null
    var json = context.get("json");
    if(json != null && json.containsKey("billDay")){
        billDay = Integer.parseInt(JSON.parse(json.getString("billDay")));
    }
    logger.info("中国银行 taskKey:{},获取到账单日：{}",context.get(LUA_TASK_KEY),billDay);
}
//解析未出账单
function analysisCreditUnDoneBills(){
    var json = context.get("json");
    var billAllData = new BillAllData();
    if (json != null && json.containsKey("unDownBill")) {
        logger.info("中国银行 taskKey:{},获取到unDownBill信息,开始解析未出账单unDownBill...",context.get(LUA_TASK_KEY));
        var unsettled = json.getJSONObject("unDownBill");
        if (null != unsettled) {
            var new_balance = new BigDecimal(0);
            var last_payment = new BigDecimal(0);
            billAllData.setBillType("UNDONE");
            billAllData.setBankName("中国银行");
            billAllData.setBillId(UUID.randomUUID().toString());
            if(null!=unBillMonth){
                var year = Integer.parseInt(unBillMonth.substring(0,unBillMonth.indexOf("/")));
                var month = Integer.parseInt(unBillMonth.substring(unBillMonth.indexOf("/")+1,unBillMonth.lastIndexOf("/")));
                var day = Integer.parseInt(unBillMonth.substring(unBillMonth.lastIndexOf("/")+1));
                if(month<12){
                    month = month+1;
                }else{
                    month = 01;
                    year = year+1;
                }
                if(month<10){
                    month = "0"+month;
                }
                billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(year+"-"+month+"-"+day));
                billAllData.setBillMonth(year+"-"+month);
            }else{
                var  sdf = new SimpleDateFormat("yyyy-MM-dd");
                var date = new Date();
                var day = date.getDate();
                var month = date.getMonth()+1;

                var cal =  Calendar.getInstance();
                var time = sdf.format(cal.getTime());
                var year = time.substring(0,4);

                if(day>billDay){
                    if(month<12){
                        month = month+1;
                    }else{
                        month = 01;
                        year = year+1;
                    }
                }
                if(month<10){
                    month = "0"+month;
                }
                billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(year+"-"+month+"-"+billDay));
                billAllData.setBillMonth(year+"-"+month);
            }
            var shop = new ArrayList();
            var cidx = 1;
            var list = unsettled.getJSONArray("crcdTransactionList");
            if (list != null && list.length > 0) {
                for (var i = 0; i < list.length; i++) {
                    var t = list.get(i);
                    var s = new Expense();
                    if(null!=t) {
                        s.setBalance(null);
                        s.setDescription(replaceAll(replaceAll(t.getString("remark"), " ", ""),"/",""));
                        var transDate = replaceAll(t.getString("transDate"), "/", "-");
                        if(null!=transDate){
                            transDate = transDate + " 00:00:00";
                            s.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(transDate));
                        }
                        s.setPostDate(yyyy_MM_dd_PARSER.parse(replaceAll(t.getString("bookDate"), "/", "-")));
                        s.setId(UUID.randomUUID().toString());
                        s.setCurrencyType("CNY");
                        s.setOrderIndex(cidx++);
                        s.setCardNum(creditCardAllData.getCardNum());
                        s.setCategory(classify(s.getDescription()));
                        if(t.getString("debitCreditFlag").equals("CRED")){
                            s.setAmountMoney(t.getBigDecimal("tranAmount").negate());
                            last_payment = last_payment.add(t.getBigDecimal("tranAmount").negate());
                        } else {
                            s.setAmountMoney(t.getBigDecimal("tranAmount"));
                            new_balance = new_balance.add(t.getBigDecimal("tranAmount"));
                        }
                        shop.add(s);
                    }
                }
            }
            billAllData.setShoppingSheets(shop);
            //总额
            var unBillTotal = json.getJSONArray("unBillTotal");
            if (unBillTotal != null && unBillTotal.length > 0) {
                for each(var object in unBillTotal ){
                    var each = object;
                    var currency = each.getString("currency");
                    if (StringUtils.isNoneBlank(currency) && currency.equals("001")) {
                        billAllData.setNewBalance(each.getBigDecimal("creditSum"));
                    } else {
                        billAllData.setUsdNewBalance(each.getBigDecimal("creditSum"));
                    }
                }
            }
            //补全信息
            billAllData.setLastPayment(last_payment);
            billAllData.setNewCharges(new_balance);
            var bills = creditCardAllData.getBills();
            var dfdate = new SimpleDateFormat("yyyy-MM");
            var nowDate = dfdate.format(new Date());
            for each(var bill in bills){
                var dueDate = bill.getPaymentDueDate();
                if(null !== dueDate){
                    logger.info("中国银行 taskKey:{} 本次 dueDate = {}",context.get(LUA_TASK_KEY),dueDate)
                    var due_date = yyyy_MM_dd_PARSER.format(dueDate);
                    if (due_date.contains(nowDate)) {
                        billAllData.setLastBalance(bill.getNewBalance()); //bill为上一个月的账单信息
                        if (bill.getNewBalance() == null || bill.getNewBalance().intValue() == 0) {
                            logger.info("中国银行 taskKey:{},上月账单无消费记录,未出账单new_balance取null",context.get(LUA_TASK_KEY));
                            billAllData.setNewBalance(null);
                        } else {
                            new_balance = new_balance.add(bill.getNewBalance());
                            billAllData.setNewBalance(new_balance);
                        }
                    }
                }else{
                    logger.info("中国银行 taskKey:{}, 本次 dueDate 为 null", context.get(LUA_TASK_KEY));
                }
            }
            if (billAllData.getCashLimit() == null || billAllData.getCashLimit().intValue() == 0) {
                billAllData.setCashLimit(creditCardAllData.getCashLimit());
            }
            if (billAllData.getCreditLimit() == null || billAllData.getCreditLimit().intValue() == 0) {
                billAllData.setCreditLimit(creditCardAllData.getCreditLimit());
            }
            creditCardAllData.getBills().add(billAllData);
        }
    }
}

//构建表头
function createCardData(){
    creditCardAllData = new CreditCardAllData();
    creditCardAllData.setCardId(UUID.randomUUID().toString());
    creditCardAllData.setCashBalance(null);
    creditCardAllData.setCashLimit(null);
    creditCardAllData.setBankName("中国银行");
    var bills = new ArrayList();
    var deposits = new ArrayList();
    creditCardAllData.setBills(bills);
    creditCardAllData.setDeposits(deposits);
    if (context.get(LUA_TASK_CARD_TYPE).equals("CREDITCARD")) {
        creditCardAllData.setCardType("信用卡");
    }else{
        creditCardAllData.setCardType("借记卡");
    }
    dataList.add(creditCardAllData);
}
/**
 *发送请求，重试3次，最终抓取为null时抛出异常
 * map  请求参数
 * headers  请求头
 * globalData 全局变量
 * key 全局变量的键值
 * description  获取的内容描述
 * flag1  result的格式[1 jsonObject/2 jsonArray/3 String]
 * flag2  获取的值是否需要存入全局变量   true需要/false不需要
 */
function retryUrl(map,headers,globalData,key,description,flag1,flag2){
    var url1;
    var array1;
    var msg;
    var times = 1;
    var result = {};
    while(null==url1&&times<=3){
        logger.info("中国银行 taskKey:{},第{}次获取{}...",context.get(LUA_TASK_KEY),Integer.parseInt(times),description);
        try{
            if(Integer.parseInt(times)!=0){
                Thread.sleep(1000);
            }
            url1 = RequestUtil.postJson("https://ebsnew.boc.cn/BII/PsnGetUserProfile.do?_locale=zh_CN", map,headers);
        }catch(e){
            logger.error("中国银行 taskKey:{} 第{}次请求{}失败：{}",context.get(LUA_TASK_KEY),Integer.parseInt(times),description,e);
        }
        times++;
    }
    if(null==url1){
        throw new BankException(BankConstants.BALO_20304_30, "发送"+description+"请求url失败");
    }else{
        array1 = JSON.parseObject(url1).getJSONArray("response");
        if(flag1.equals("1")){
            msg = array1[0].getJSONObject("result");
        }else if(flag1.equals("2")){
            msg = array1[0].getJSONArray("result");
        }else if(flag1.equals("3")){
            msg = array1[0].getString("result");
        }
    }
    if(null==msg){
        var message = array1[0].getJSONObject("error").getString("message");
        result.data = message;
        result.flag = false;
    }else{
        result.data = msg;
        result.flag = true;
    }
    if(!result.flag){
        logger.info(description+key+":"+result.data);
        throw new BankException(BankConstants.BALO_20304_30, result.data);
    }else{
        var data = result.data;
        logger.info(description+key+":"+JSON.toJSONString(data));
        if(flag2){
            globalData[key] = data;
        }
    }
    return result;
}
/**
 *发送请求，重试3次，最终抓取为null时不抛出异常
 * map  请求参数
 * headers  请求头
 * globalData 全局变量
 * key 全局变量的键值
 * description  获取的内容描述
 * flag1  result的格式[1 jsonObject/2  jsonArray/3  String]
 * flag2  获取的值是否需要存入全局变量   true需要/false不需要
 */
function retryContinueUrl(map,headers,globalData,key,description,flag1,flag2){
    var url;
    var array1;
    var msg;
    var times = 1;
    var result = {};
    while(null==url&&times<=3){
        logger.info("中国银行 taskKey:{},第{}次获取{}...",context.get(LUA_TASK_KEY),Integer.parseInt(times),description);
        try{
            if(Integer.parseInt(times)!=0){
                Thread.sleep(1000);
            }
            url = RequestUtil.postJson("https://ebsnew.boc.cn/BII/PsnGetUserProfile.do?_locale=zh_CN", map,headers);
        }catch(e){
            logger.error("中国银行 taskKey:{}, 第{}次请求{}失败：{}",context.get(LUA_TASK_KEY),Integer.parseInt(times),description,e);
        }
        times++;
    }
    if(null!=url){
        array1 = JSON.parseObject(url).getJSONArray("response");
        if(flag1.equals("1")){
            msg = array1[0].getJSONObject("result");
        }else if(flag1.equals("2")){
            msg = array1[0].getJSONArray("result");
        }else if(flag1.equals("3")){
            msg = array1[0].getString("result");
        }
        if(null==msg){
            var message = array1[0].getJSONObject("error").getString("message");
            result.data = message;
            result.flag = false;
        }else{
            result.data = msg;
            result.flag = true;
        }
    }else{
        result.data = "发送"+description+"请求url失败";
        result.flag = false;
    }
    if(!result.flag){
        logger.info(description+key+":"+result.data);
    }else{
        var data = result.data;
        logger.info(description+key+":"+JSON.toJSONString(data));
        if(flag2){
            globalData[key] = data;
        }
    }
    return result;
}

//中国银行货币判断
function getZhongguoCurrencyType(code) {
    switch (code) {
        case "001":
            return "CNY";
        default:
            break;
    }
    return "CNY";
}

function parseInstallment(i, t, billid) {
    var desc = t.getString("dealDesc");
    var isinst = this.isInstallment(desc);
    if (isinst > 1) {
        i.setInstallmentType(classify(desc));
        i.setBillId(UUID.randomUUID().toString());
        i.setCurrencyType(t.getString("acntType"));
        i.setShoppingsheetId(billid);
        if (isinst == 2) {
            i.setHandingFee(t.getBigDecimal("dealCnt"));
            i.setHandingfeeDesc(desc);
        }
        if (isinst == 3) {
            var rgx = "^(\\d+)/(\\d+).*$";
            i.setCurrentMonth(getGroup1(rgx, desc))
            var total = getGroupByIndex(rgx, desc, 2)
            var totalMonth
            if(total.length() >= 2){
                totalMonth = total.substring(0, 2);
                i.setTotalMonth(totalMonth);
            }
            i.setInstallmentDesc(desc);
            if(t.getString("loanSign").equals("CRED")){
                i.setAmountMoney(t.getBigDecimal("dealCnt").negate());
            } else {
                i.setAmountMoney(t.getBigDecimal("dealCnt"));
            }
            i.setPostDate(yyyy_MM_dd_PARSER.parse(replaceAll(t.getString("checkDt"),"/", "-")));
            var trans_dateStr = replaceAll(t.getString("dealDt"),"/", "-");
            if(null!=trans_dateStr){
                var trans_date = trans_dateStr + " 00:00:00";
                i.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date));
            }
        }
    }

}

function isInstallment(desc) {
    var type = 0;
    if (desc.contains("分期")) {
        type = 1;
        if (desc.contains("手续费")) {
            type = 2;
        }
    }
    var rgx = "^\\d+/\\d+.*$";
    if (isMatch(rgx,desc)) {
        type = 3;
    }
    return type;
}

// 判断是否全部数字
function isAllNum(str) {
    if (StringUtils.isEmpty(str))
        return false;
    var regex = "^\\d+$";
    return  isMatch(regex,str)
}

function replaceAll(str, oldStr, newStr){
    if(null==str){
        return null;
    }
    var temp = '';
    temp = str.replace(oldStr, newStr);
    if(temp.indexOf(oldStr)!=-1){
        temp = replaceAll(temp, oldStr, newStr);
    }
    return temp;
};

var luaFuncs = {

    typeUsername: function (username) {
        var map = new LinkedHashMap();
        map.put("method", "typeUsername");
        map.put("username", username);
        return sendAndReceive(map);
    },
    checkUsername: function () {
        var map = new LinkedHashMap();
        map.put("method", "checkUsername");
        return sendAndReceive(map);
    },
    inputpwd: function (pwd) {
        var map = new LinkedHashMap();
        map.put("method", "inputpwd");
        map.put("password", pwd);
        return sendAndReceive(map);
    },
    inputcaptcha: function (captcha) {
        var map = new LinkedHashMap();
        map.put("method", "inputcaptcha");
        map.put("captcha", captcha);
        return sendAndReceive(map);
    },
    presslogin: function () {
        var map = new LinkedHashMap();
        map.put("method", "presslogin");
        return sendAndReceive(map);
    },
    loginok: function (loginStyle) {
        var map = new LinkedHashMap();
        map.put("loginStyle", loginStyle);
        map.put("method", "loginok");
        return sendAndReceive(map);
    },
    getimage_by_id:function (string1) {
        var map = new LinkedHashMap();
        map.put("method", "getimage_by_id");
        map.put("id", string1);
        return sendAndReceive(map);
    },
    isCaptcha:function () {
        var map = new LinkedHashMap();
        map.put("method", "isCaptcha");
        return sendAndReceive(map);
    },
    getLoginCookie: function () {
        var map = new LinkedHashMap();
        map.put("method", "getLoginCookie");
        return sendAndReceive(map);
    },
}